package com.oriole.admin.config.aspect;

import com.alibaba.fastjson.JSONObject;
import com.oriole.admin.feign.ISysOperationLogService;
import com.oriole.common.annotation.OperationLog;
import com.oriole.common.util.OrioleStringUtils;
import com.oriole.common.util.ServletUtils;
import com.oriole.entity.sys.SysOperationLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2020/11/7 21:52
 * Description:
 */
@Aspect
@Component
public class OperationLogAspect {

    @Resource
    private ISysOperationLogService sysOperationLogService;

    private static final Logger log = LoggerFactory.getLogger(OperationLogAspect.class);

    @Pointcut("@annotation(com.oriole.common.annotation.OperationLog)")
    public void pointCut() {

    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "pointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "pointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    private void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        OperationLog operationLog = getOperationLog(joinPoint);
        if (operationLog == null) {
            return;
        }
        SysOperationLog sysOperationLog = new SysOperationLog();
        sysOperationLog.setTitle(operationLog.title());
        sysOperationLog.setBusinessType(operationLog.businessType().name());
        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        sysOperationLog.setMethodName(className + "." + methodName + "()");
        // 设置请求方式
        sysOperationLog.setRequestMethod(ServletUtils.getRequest().getMethod());
        // 请求URL
        sysOperationLog.setUrl(ServletUtils.getRequest().getRequestURI());
        // Ip地址
        sysOperationLog.setIp(ServletUtils.getIp());
        // 地点
        sysOperationLog.setLocation(ServletUtils.getLocationByIp());
        // 请求参数
        if (operationLog.saveRequestParams()) {
            sysOperationLog.setRequestParams(getRequestParams());
        }
        // 结果
        sysOperationLog.setResult(OrioleStringUtils.substring(jsonResult.toString(), 0, 4000));
        // 错误信息
        if (e != null) {
            sysOperationLog.setErrorMsg(OrioleStringUtils.substring(e.getMessage(), 0, 4000));
        }
        sysOperationLogService.save(sysOperationLog);
    }

    private OperationLog getOperationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(OperationLog.class);
        }
        return null;
    }

    /**
     * 获取请求的参数，放到log中
     */
    private String getRequestParams() {
        Map<String, String[]> parameterMap = ServletUtils.getRequest().getParameterMap();
        if (OrioleStringUtils.isNotEmpty(parameterMap)) {
            String requestParams = JSONObject.toJSONString(parameterMap);
            return OrioleStringUtils.substring(requestParams, 0, 4000);
        }
        return null;
    }

}
